import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { graphql, compose } from 'react-apollo';
import gql from 'graphql-tag';
import { propType, filter } from 'graphql-anywhere';
import { TouchableOpacity, ActivityIndicator, ScrollView, View, Text, StyleSheet } from 'react-native';
import { Button, List, CheckBox, ListItem, Icon } from 'react-native-elements';
import { Calendar } from 'react-native-calendars';
import { executor, primaryColor } from '../utils';
import SlotListItem from './SlotListItem';
import ClothGridItem from './ClothGridItem';
import Loader from '../widgets/Loader';
import moment from 'moment';

const styles = StyleSheet.create({
  container: {
    flex: 1
  },
  spinner: {
    marginTop: 60
  },
  list: {
    marginTop: 0,
    marginBottom: 100
  },
  header: {
    flex: 1,
    margin: 8,
    color: 'gray'
  },
  row: {
    backgroundColor: 'white',
    flexDirection: 'row',
    alignItems: 'center',
    paddingVertical: 4,
    paddingHorizontal: 4,
  },
  express: {
    paddingHorizontal: 4
  },
  button: {
    flexDirection: 'row',
    alignItems: 'center'
  },
  textContainer: {
    padding: 8
  },
  buttonText: {
    color: primaryColor,
    fontSize: 16
  },
  subButtonText: {
    color: 'gray',
    fontSize: 14
  }
});

class OrderDatePanel extends Component {
  state = {};
  componentDidMount() {
    if (this.props.selectDate) {
      const date = moment(this.props.selectDate);
      this.onSelectDate({year: date.year(), month: date.month()+1,
        day: date.date(), hour: date.hour()});
    }
  }
  componentWillReceiveProps(nextProps) {
    if (!nextProps.selectDate&&nextProps.orderDates&&nextProps.orderDates[0]) {
      const date = nextProps.orderDates[0];
      this.onSelectDate({year: date.year, month: date.month+1, day: date.date});
    } else if (nextProps.selectDate&&nextProps.orderDates&&nextProps.orderDates[0]) {
      const selectDate = moment(nextProps.selectDate);
      const startDate = moment([nextProps.orderDates[0].year, nextProps.orderDates[0].month,
        nextProps.orderDates[0].date]);
      const endDate = moment([nextProps.orderDates[nextProps.orderDates.length-1].year,
        nextProps.orderDates[nextProps.orderDates.length-1].month, nextProps.orderDates[nextProps.orderDates.length-1].date, 23]);

      if (selectDate.isBefore(startDate)||selectDate.isAfter(endDate)) {
        const date = nextProps.orderDates[0];
        this.onSelectDate({year: date.year, month: date.month+1, day: date.date});
      } else if (this.props.express!==nextProps.express) {
        const date = nextProps.orderDates[0];
        this.onSelectDate({year: date.year, month: date.month+1, day: date.date});
      }
    }
  }
  onSelectDate = ({year, month, day, hour=0}) => {
    const date = moment([year, month-1, day, hour]).toDate().toString();
    this.props.onSelectDate(date);
    if (!this.props.business) {
      executor(this.props.loadTimeSlot, date)
        .then(({res}) => {
          if (res) {
            this.setState({
              slots: res.loadTimeSlot||[]
            });
          }
          this.setState({loading: false});
        })
      this.setState({loading: true});
    }
  }
  onSelectSlot = (hour) => {
    const date = moment(this.props.selectDate);
    this.props.onSelectDate(date.hour(hour).toDate().toString());
  }
  onLockerBag = () => {
    const navigation = this.props.navigation;
    navigation.navigate('LockerBag', {selectMode: true, onSelect: (lockerBag) => {
      setTimeout(() => {
        const found = this.props.navigation.state.params.items.find(item => item.id===lockerBag.id);
        if (!found) {
          navigation.setParams({...this.props.navigation.state.params,
            items: [...this.props.navigation.state.params.items, lockerBag]});
        }
      }, 300);
    }});
  }
  render() {
    const { chinese, isPickup, type, business, items, express=false, isFlexible, lockerBag, user } = this.props;
    const selectDate = this.props.selectDate&&moment(this.props.selectDate);
    const select = selectDate&&selectDate.format('YYYY-MM-DD');

    return this.props.loading?<Loader/>:(
      <ScrollView>
        <Calendar current={select} hideExtraDays selected={select&&[select]} theme={{
          selectedDayBackgroundColor: primaryColor,
          todayTextColor: primaryColor,
          dotColor: 'white',
          arrowColor: primaryColor,}}
          markedDates={this.props.markedDates} onDayPress={this.onSelectDate}/>
        {business?
          <List>
            <ListItem hideChevron subtitle={chinese?`企业账户无需选择取送时间段，请选好日期后点击右上角的'继续'按钮`:`For business account there is no need to select time slot, please press the upper right 'Next' button to continue.`}/>
          </List>:
          <View style={styles.row}>
            <Text style={styles.header}>{chinese?'选择时间':`Select Time Slot`}</Text>
            {(type==='laundry'||type==='premiumlaundry')&&(isPickup?
              (lockerBag&&user&&!user.hasLockerBag&&items&&!items.find(item=>item.id===lockerBag.id)&&<TouchableOpacity style={styles.button} onPress={this.onLockerBag}>
                <Icon name='fiber-new' color={primaryColor}/>
                <View style={styles.textContainer}>
                  <Text style={styles.buttonText}>{chinese?'免费使用KnocKnocK锁包':'Try Locker Bag For Free'}</Text>
                  <Text style={styles.subButtonText}>{chinese?'节省您的时间':'Free your time'}</Text>
                </View>
              </TouchableOpacity>):
              <CheckBox title={chinese?'加急订单':'Express Order'} checked={express} onPress={this.props.onToggleExpress}/>)
            }
          </View>
        }
        {this.state.loading?<ActivityIndicator style={styles.spinner}/>:
          <List containerStyle={styles.list}>
            {this.state.slots&&
              this.state.slots.map((timeSlot, index) =>
                <SlotListItem key={index} timeSlot={filter(SlotListItem.fragments.timeSlot, timeSlot)}
                  isflexible={isFlexible} onToggleFlixable={this.props.onToggleFlixable}
                  checked={(selectDate&&selectDate.hour()===timeSlot.value)?true:false} onSelect={this.onSelectSlot}/>)
            }
          </List>
        }
      </ScrollView>
    );
  }
}

export default compose(
  graphql(gql`
    mutation loadTimeSlot($isPickup:Boolean,$addressId:String!,$date:String!,$items:[OrderItemInput]) {
      loadTimeSlot(isPickup:$isPickup,addressId:$addressId,date:$date,items:$items) {
        value
        ...SlotListItem
      }
    }
    ${SlotListItem.fragments.timeSlot}
  `, {
    props: ({ownProps:{isPickup, addressId, items}, mutate}) => {
      return {
        loadTimeSlot: (date) => mutate({variables:{isPickup,addressId,items,date}})
      };
    }
  }),
  graphql(gql`
    query orderDates($isPickup:Boolean!,$date:String!,$items:[OrderItemInput],$addressId:String!,$express:Boolean) {
      orderDates(isPickup:$isPickup,date:$date,items:$items,addressId:$addressId,express:$express) {
        year
        month
        date
      }
      user {
        id
        hasLockerBag
      }
      lockerBag {
        ...ClothGridItem
      }
    }
    ${ClothGridItem.fragments.cloth}
  `, {
    options: ({isPickup, addressId, date, items, express=false}) => {
      return {
        variables: {
          isPickup,
          addressId,
          items,
          date,
          express
        }
      };
    },
    props: ({ownProps, data: {orderDates, user, lockerBag, loading}}) => {
      let markedDates = {};
      if (orderDates) {
        const daysInMonth = moment([orderDates[0].year,orderDates[0].month,1]).daysInMonth();
        for (let index = 1; index <= daysInMonth; index++) {
          markedDates[moment([orderDates[0].year,orderDates[0].month,index]).format('YYYY-MM-DD')] = {disabled: true};
        }

        orderDates.map(item => {
          markedDates[moment([item.year,item.month,item.date]).format('YYYY-MM-DD')] = {marked: true};
        });
      }

      return {
        user,
        lockerBag,
        markedDates,
        orderDates,
        loading
      };
    }
  })
)(OrderDatePanel);
